package org.example;


import org.example.segmentation.Range;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DataSynchronization {

  public void syncData(Connection sourceConn, Connection targetConn, String tableName, Range range, String segmentField) throws SQLException {
    String tempTableName = tableName + "_temp";

    // 1. 清空临时表
    String clearTempTableSql = String.format("TRUNCATE TABLE %s", tempTableName);
    try (Statement stmt = targetConn.createStatement()) {
      stmt.executeUpdate(clearTempTableSql);
    }

    // 2. 从源表同步数据到临时表
    String insertTempTableSql = String.format(
        "INSERT INTO %s SELECT * FROM %s WHERE %s BETWEEN ? AND ?",
        tempTableName, tableName, segmentField
    );
    try (PreparedStatement pstmt = targetConn.prepareStatement(insertTempTableSql)) {
      pstmt.setString(1, range.getStart());
      pstmt.setString(2, range.getEnd());
      pstmt.executeUpdate();
    }

    // 3. 从临时表导入数据到目标表
    String insertTargetTableSql = String.format(
        "INSERT INTO %s SELECT * FROM %s",
        tableName, tempTableName
    );
    try (Statement stmt = targetConn.createStatement()) {
      stmt.executeUpdate(insertTargetTableSql);
    }
  }
}

